package com.tzy.user;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tzy.common.entity.WebContent;
import com.tzy.common.utils.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.Test;

import javax.annotation.Resource;
import java.io.IOException;

@Slf4j
public class InsertDocument {
    //    @Resource
//    private RestHighLevelClient restHighLevelClient;
    private static String host = "172.23.68.127";

    @Test
    public void testInsert() throws IOException {
        // 创建客户端对象
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost(host, 9200, "http")));
        IndexRequest request = new IndexRequest();
        request.index("es_db").id("1001");

        WebContent webContent = new WebContent();
        webContent.setId(RandomUtil.getCheckCode());
        webContent.setTitle("华为P50");
        webContent.setPrice("3499.98");
        webContent.setShopName("华为官方旗舰店");
        //向 ES插入数，必须转为JSON
        ObjectMapper mapper = new ObjectMapper();
        String userJson = mapper.writeValueAsString(webContent);
        request.source(userJson, XContentType.JSON);
        IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
        log.info("插入数据结果:{}", JSON.toJSONString(response));
    }

}
